<template>
  <Dialog v-model="dialogVisible" title="题目导入" width="800px">
    <el-steps :active="currentStep" align-center style="margin-bottom: 30px;">
      <el-step title="选择文件" description="上传Excel文件" />
      <el-step title="数据预览" description="检查导入数据" />
      <el-step title="导入结果" description="查看导入结果" />
    </el-steps>

    <!-- 步骤1：文件上传 -->
    <div v-if="currentStep === 0">
      <el-form :model="importForm" :rules="importRules" ref="importFormRef" label-width="120px">
        <el-form-item label="题目分类" prop="categoryId">
          <el-select v-model="importForm.categoryId" placeholder="请选择题目分类">
            <el-option label="基础理论" value="1" />
            <el-option label="实操技能" value="2" />
            <el-option label="安全知识" value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="适用职业" prop="professionId">
          <el-select v-model="importForm.professionId" placeholder="请选择适用职业">
            <el-option label="电工" value="1" />
            <el-option label="焊工" value="2" />
            <el-option label="车工" value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="技能等级" prop="skillLevel">
          <el-select v-model="importForm.skillLevel" placeholder="请选择技能等级">
            <el-option label="初级" :value="1" />
            <el-option label="中级" :value="2" />
            <el-option label="高级" :value="3" />
            <el-option label="技师" :value="4" />
            <el-option label="高级技师" :value="5" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <el-divider content-position="left">上传文件</el-divider>
      
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :auto-upload="false"
        accept=".xlsx,.xls"
        :limit="1"
        :on-change="handleFileChange"
        :file-list="fileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传xlsx/xls文件，且不超过10MB
          </div>
        </template>
      </el-upload>
      
      <el-divider content-position="left">模板下载</el-divider>
      <el-alert
        title="导入说明"
        type="info"
        :closable="false"
        style="margin-bottom: 15px;"
      >
        <p>1. 请先下载导入模板，按照模板格式填写题目数据</p>
        <p>2. 表格列包括：题目内容、题目类型、选项A、选项B、选项C、选项D、正确答案、解析、难度等级</p>
        <p>3. 题目类型：1-单选题，2-多选题，3-判断题，4-填空题，5-简答题</p>
        <p>4. 难度等级：1-简单，2-中等，3-困难</p>
      </el-alert>
      
      <el-button type="primary" @click="downloadTemplate">
        <el-icon><Download /></el-icon>
        下载导入模板
      </el-button>
    </div>

    <!-- 步骤2：数据预览 -->
    <div v-if="currentStep === 1">
      <el-alert
        :title="`共解析出 ${previewData.length} 条题目数据`"
        type="success"
        :closable="false"
        style="margin-bottom: 15px;"
      />
      
      <el-table 
        :data="previewData.slice(0, 10)" 
        border 
        style="width: 100%"
        max-height="400"
      >
        <el-table-column prop="questionContent" label="题目内容" width="300" show-overflow-tooltip />
        <el-table-column prop="questionType" label="题目类型" width="100">
          <template #default="{ row }">
            {{ getQuestionTypeName(row.questionType) }}
          </template>
        </el-table-column>
        <el-table-column prop="options" label="选项" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatOptions(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="correctAnswer" label="正确答案" width="100" />
        <el-table-column prop="difficulty" label="难度" width="80">
          <template #default="{ row }">
            <el-tag :type="getDifficultyColor(row.difficulty)">
              {{ getDifficultyName(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.valid ? 'success' : 'danger'">
              {{ row.valid ? '有效' : '无效' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="previewData.length > 10" style="margin-top: 10px; color: #909399;">
        仅显示前10条数据，实际将导入 {{ previewData.length }} 条
      </div>
      
      <el-divider content-position="left" v-if="errorMessages.length > 0">错误信息</el-divider>
      <el-alert
        v-for="(error, index) in errorMessages"
        :key="index"
        :title="error"
        type="error"
        :closable="false"
        style="margin-bottom: 10px;"
      />
    </div>

    <!-- 步骤3：导入结果 -->
    <div v-if="currentStep === 2">
      <el-result
        :icon="importResult.success ? 'success' : 'error'"
        :title="importResult.success ? '导入成功' : '导入失败'"
        :sub-title="importResult.message"
      >
        <template #extra>
          <div style="margin-bottom: 20px;">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="总数据量">{{ importResult.total }}</el-descriptions-item>
              <el-descriptions-item label="成功导入">
                <span style="color: #67c23a;">{{ importResult.successCount }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="导入失败">
                <span style="color: #f56c6c;">{{ importResult.failCount }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="跳过数量">
                <span style="color: #e6a23c;">{{ importResult.skipCount }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div v-if="importResult.failedData && importResult.failedData.length > 0">
            <el-divider content-position="left">失败数据</el-divider>
            <el-table :data="importResult.failedData" border style="width: 100%" max-height="300">
              <el-table-column prop="row" label="行号" width="80" />
              <el-table-column prop="questionContent" label="题目内容" show-overflow-tooltip />
              <el-table-column prop="errorMessage" label="错误原因" show-overflow-tooltip />
            </el-table>
          </div>
        </template>
      </el-result>
    </div>

    <template #footer>
      <div v-if="currentStep === 0">
        <el-button @click="nextStep" type="primary" :disabled="fileList.length === 0">下一步</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
      <div v-else-if="currentStep === 1">
        <el-button @click="prevStep">上一步</el-button>
        <el-button @click="startImport" type="primary" :loading="importing" :disabled="!hasValidData">
          开始导入
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
      <div v-else-if="currentStep === 2">
        <el-button @click="resetImport" type="primary">重新导入</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { UploadFilled, Download } from '@element-plus/icons-vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const currentStep = ref(0)
const importing = ref(false)
const uploadRef = ref()
const importFormRef = ref()

const importForm = ref({
  categoryId: '',
  professionId: '',
  skillLevel: undefined
})

const importRules = ref({
  categoryId: [{ required: true, message: '请选择题目分类', trigger: 'change' }],
  professionId: [{ required: true, message: '请选择适用职业', trigger: 'change' }],
  skillLevel: [{ required: true, message: '请选择技能等级', trigger: 'change' }]
})

const fileList = ref([])
const previewData = ref([])
const errorMessages = ref([])
const importResult = ref({
  success: false,
  message: '',
  total: 0,
  successCount: 0,
  failCount: 0,
  skipCount: 0,
  failedData: []
})

const hasValidData = computed(() => {
  return previewData.value.some(item => item.valid)
})

const getQuestionTypeName = (type: number) => {
  const typeMap = { 1: '单选题', 2: '多选题', 3: '判断题', 4: '填空题', 5: '简答题' }
  return typeMap[type] || '未知'
}

const getDifficultyName = (difficulty: number) => {
  const difficultyMap = { 1: '简单', 2: '中等', 3: '困难' }
  return difficultyMap[difficulty] || '未知'
}

const getDifficultyColor = (difficulty: number) => {
  const colorMap = { 1: 'success', 2: 'warning', 3: 'danger' }
  return colorMap[difficulty] || 'info'
}

const formatOptions = (row: any) => {
  if (row.questionType === 3) return '是/否'
  return `A:${row.optionA || ''} B:${row.optionB || ''} C:${row.optionC || ''} D:${row.optionD || ''}`
}

const handleFileChange = (file: any) => {
  if (file.raw) {
    const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                 || file.raw.type === 'application/vnd.ms-excel'
    if (!isExcel) {
      ElMessage.error('只能上传Excel文件!')
      fileList.value = []
      return false
    }
    
    const isLt10M = file.raw.size / 1024 / 1024 < 10
    if (!isLt10M) {
      ElMessage.error('上传文件大小不能超过10MB!')
      fileList.value = []
      return false
    }
  }
}

const downloadTemplate = () => {
  // TODO: 实现模板下载
  console.log('下载题目导入模板')
  ElMessage.success('模板下载功能开发中...')
}

const nextStep = async () => {
  if (currentStep.value === 0) {
    const valid = await importFormRef.value.validate()
    if (!valid) return
    
    if (fileList.value.length === 0) {
      ElMessage.error('请选择要导入的文件')
      return
    }
    
    // 解析文件内容
    parseExcelFile()
    currentStep.value = 1
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const parseExcelFile = () => {
  // 模拟解析Excel文件
  previewData.value = [
    {
      questionContent: '电工作业中，安全电压是指不会对人体造成伤害的电压，其值为？',
      questionType: 1,
      optionA: '12V',
      optionB: '24V',
      optionC: '36V',
      optionD: '48V',
      correctAnswer: 'C',
      explanation: '安全电压是指不会对人体造成伤害的电压，一般为36V以下',
      difficulty: 1,
      valid: true
    },
    {
      questionContent: '以下哪些是电工常用的安全防护用品？',
      questionType: 2,
      optionA: '安全帽',
      optionB: '绝缘手套',
      optionC: '安全带',
      optionD: '绝缘鞋',
      correctAnswer: 'ABCD',
      explanation: '这些都是电工作业的必要安全防护用品',
      difficulty: 2,
      valid: true
    },
    {
      questionContent: '直流电比交流电更安全',
      questionType: 3,
      correctAnswer: '错误',
      explanation: '在相同电压下，直流电和交流电的危险性基本相同',
      difficulty: 2,
      valid: true
    }
  ]
  
  errorMessages.value = []
}

const startImport = async () => {
  importing.value = true
  
  // 模拟导入过程
  setTimeout(() => {
    importResult.value = {
      success: true,
      message: '题目导入完成',
      total: previewData.value.length,
      successCount: previewData.value.length - 1,
      failCount: 1,
      skipCount: 0,
      failedData: [
        {
          row: 5,
          questionContent: '错误的题目内容',
          errorMessage: '题目内容不能为空'
        }
      ]
    }
    
    importing.value = false
    currentStep.value = 2
  }, 2000)
}

const resetImport = () => {
  currentStep.value = 0
  fileList.value = []
  previewData.value = []
  errorMessages.value = []
  importResult.value = {
    success: false,
    message: '',
    total: 0,
    successCount: 0,
    failCount: 0,
    skipCount: 0,
    failedData: []
  }
  
  // 重置表单
  importForm.value = {
    categoryId: '',
    professionId: '',
    skillLevel: undefined
  }
}

const open = () => {
  dialogVisible.value = true
  resetImport()
}

defineExpose({ open })
</script>

<style scoped>
.upload-demo {
  margin: 20px 0;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style> 